<?php

namespace app\Home\controller;

//公共控制器
use app\common\controller\Homecontroller;

use think\Cookie;

class User extends Homecontroller
{
    public function __construct()
    {
        //手动把父类的方法获取过来
        parent::__construct();

        //用户模型
        $this->UserModel = model('User.User');

        //地区模型
        $this->RegionModel = model('Region');
    }
    public function index()
    {
        $id = $this->request->param('userid', 0);

        $UserInfo = $this->UserModel->find($id);

        // 首页传过来的ID与登陆户是否一致
        if ($UserInfo) {
            $this->assign(['UserInfo' => $UserInfo]);
            // 渲染到另一个模块文件
            return  $this->fetch('consumer');
        } else {
            $LoginUser = Cookie::get('LoginUser');
            $UserInfo = $this->UserModel->where(['id' => $LoginUser['id']])->find();
            $this->assign([
                'LoginUser' => $UserInfo,
            ]);
            return  $this->fetch();
        }
    }

    // 用户设置
    public function user()
    {
        $LoginUser = Cookie::get('LoginUser');

        $UserInfo = $this->UserModel->where(['id' => $LoginUser['id']])->find();

        if(!$UserInfo){

            $this->error('没有当前用户，请重新登陆');
            exit;
        }

        if($this->request->isPost()){
            $params = $this->request->param();
            $action = $this->request->param('action', '');
            
            // 我的资料
            if ($action == 'profile'){
                
                $data=[
                    'id' => $LoginUser['id'],
                    'email' => $UserInfo['email'],
                    'sex' => $params['sex'],
                    'nickname' => $params['nickname'],
                    'province' =>$params['province'],
                    'city' =>$params['city'],
                    'district' => $params['district'],
                    'content' => $params['content']
                ];

                $resutlprofile = $this->UserModel->isUpdate()->save($data);
                // echo $this->UserModel->getlastsql();
                // exit;

                if($resutlprofile === FALSE){
                    $this->error($this->UserModel->getError());
                    exit;
                } else{
                    //设置一个保存cookie信息
                    $res = [
                        'id'=>$LoginUser['id'],
                        'nickname'=>$params['nickname'] ? $params['nickname'] : $UserInfo['nickname'],
                        'vip'=>$LoginUser['vip'],
                        'auth'=>$LoginUser['auth'],
                        'avatar'=>is_file($UserInfo['avatar']) ? '/'.$UserInfo['avatar'] : '/assets/home/images/avatar.jpg',
                        'cover'=>is_file($UserInfo['cover']) ? '/'.$UserInfo['cover'] : '/assets/home/images/back.jpg'
                    ];

                    Cookie::set('LoginUser', $res);
                    $this->success('更新个人资料成功');
                    exit;
                }
                
            }

            // 密码
            if ($action == 'password'){

                $nowpass =  $this->request->param('nowpass', '');
                $password = $this->request->param('password', '');
                $repass = $this->request->param('repass', '');
                // 密码盐
                $salt = $UserInfo['salt'];
                // 加密当前密码
                $nowpass = md5($nowpass.$salt);

                // 判断当前密码
                if($nowpass != $UserInfo['password']){

                    $this->error('当前密码输入错误');
                    exit;
                }

                //判断是否等于原来的密码
                $passwords = md5($password.$salt);
                if($passwords == $nowpass){
                    $this->error('新密码不能设置为当前密码');
                    exit;
                }

                //判断密码和确认密码是否一致
                if($password != $repass){
                    $this->error('密码和确认密码不一致');
                    exit;
                }

                // 重新生成了密码盐
                $salts = randstr(10);

                // 新密码加密
                $password = md5($password.$salts);

                $data = [
                    'id' => $LoginUser['id'],
                    'password' => $password,
                    'salt' => $salts
                ];

                $resutlpassworld = $this->UserModel->isUpdate()->save($data);

                if($resutlpassworld === FALSE){
                    $this->error($this->UserModel->getError());
                    exit;
                } else{
                    $this->success('密码修改成功');
                    exit;
                }
            }

            // 我的头像
            if($action == 'avatar'){

                // 图片上传
                $imgUrl = upload('avatar');

                if($imgUrl === FALSE)
                {
                    $this->error('修改头像失败');
                    exit;
                }

                // 组装数据
                $data = [
                    'id' => $LoginUser['id'],
                    'avatar' => "uploads/".$imgUrl
                ];

                $resutlImg = $this->UserModel->isUpdate()->save($data);

                if($resutlImg === FALSE){

                    //上传上来的图片删除了
                    @is_file($data['avatar']) && @unlink($data['avatar']);

                    $this->error($this->UserModel->getError());
                    exit;
                } else{
                    
                    //修改成功后，将原来的图片删除
                    $avatar = ltrim($UserInfo['avatar'],"/");
                    @is_file($avatar) && @unlink($avatar);

                    //设置一个保存cookie信息
                    $cookie = [
                        'id'=>$LoginUser['id'],
                        'nickname'=>$LoginUser['nickname'],
                        'vip'=>$LoginUser['vip'],
                        'auth'=>$LoginUser['auth'],
                        'avatar'=>is_file($data['avatar']) ? '/'.$data['avatar'] : '/assets/home/images/avatar.jpg',
                        'cover'=>is_file($UserInfo['cover']) ? '/'.$UserInfo['cover'] : '/assets/home/images/back.jpg'
                    ];

                    Cookie::set('LoginUser',$cookie);

                    $this->success('头像成功');
                    exit;
                }
            }

            // 我的封面
            if($action == 'cover'){

                // 图片上传
                $imgUrl = upload('cover');

                if($imgUrl === FALSE)
                {
                    $this->error('修改封面失败');
                    exit;
                }

                // 组装数据
                $data = [
                    'id' => $LoginUser['id'],
                    'cover' => "uploads/".$imgUrl
                ];
                $resutlImg = $this->UserModel->isUpdate()->save($data);

                if($resutlImg === FALSE){

                    //上传上来的图片删除了
                    @is_file($data['cover']) && @unlink($data['cover']);

                    $this->error($this->UserModel->getError());
                    exit;
                } else{
                    
                    //修改成功后，将原来的图片删除
                    $avatar = ltrim($UserInfo['cover'],"/");
                    @is_file($avatar) && @unlink($avatar);

                    //设置一个保存cookie信息
                    $cookie = [
                        'id'=>$LoginUser['id'],
                        'nickname'=>$LoginUser['nickname'],
                        'vip'=>$LoginUser['vip'],
                        'auth'=>$LoginUser['auth'],
                        'cover'=>is_file($data['cover']) ? '/'.$data['cover'] : '/assets/home/images/back.jpg',
                        'avatar'=>is_file($UserInfo['avatar']) ? '/'.$UserInfo['avatar'] : '/assets/home/images/avatar.jpg'
                    ];
                    Cookie::set('LoginUser',$cookie);
                    $this->success('封面成功');
                    exit;
                }
            }
            

        }
       
        //查询地区表的省份数据
        $province = $this->RegionModel->where(['grade' => 1])->select();

        //判断当前这个用户是否有选择省份
        if(empty($UserInfo['province'])){

            $city = [];
        } else{

            $city = $this->RegionModel->where(['parentid' => $UserInfo['province']])->select();
        }

        //判断当前用户是否有选择城市
        if(empty($UserInfo['city'])){
            $district = [];
        } else{
            $district = $this->RegionModel->where(['parentid' => $UserInfo['city']])->select();
            // echo $this->RegionModel->getlastsql();
            // exit;
        }
        $setup = $this->request->param('setup',false);

        // var_dump($district);
        // exit;
        // assign()渲染到前端, 个人信息，省份，市，区
        $this->assign([
            'LoginUser' => $UserInfo,
            'province' => $province,
            'city' => $city,
            'district' => $district,
            'setup' => $setup

        ]);

        return  $this->fetch();
    }


    // 查询市 区 
    public function area(){
        if($this->request->isPost()){
            $code = $this->request->param('code');

            $result = $this->RegionModel->where(['parentid' => $code])->select();

           //返回json数据
           return json($result);
        }
    }

    // 发送邮件
    public function email(){
        if($this->request->isPost()){

            $email = $this->request->param('email','');

            //返回的结果
            $success = [
                'result'=>false,
                'msg'=>''
            ];

            if(empty($email))
            {
                $success['result'] = false;
                $success['msg'] = '邮箱不能为空';
                exit;
            }

            //将邮箱进行md5加密
            $emails = md5($email);

            //组装信息
            $msg = "<a href='http://www.ask.com/home/index/email?email=$emails'>点击免费邮箱验证</a>";

            //调用公共函数库里面邮箱发送方法
            $result = send($email, $msg);

            if($result){
                $success['result'] = true;
                $success['msg'] = '发送邮件成功，请注意查收';
            } else{
                $success['result'] = false;
                $success['msg'] = '邮件发送失败，请重新发送';
            }

            return json($success);
        }
        exit;
    }
}
